<?php

defined('_INSTALL') or die('Restricted access');
require_once 'includes/helpers.php';
require_once 'includes/request.php';
require_once 'includes/session.php';

class Installer {
    
    public static function run() {
        Session::init();
        $step = self::getStep();
        try {
            self::$step();
        } catch (Exception $e) {
            die('<div style="color:red;font-size:20px;font-weight:bold;text-align:center;">Fatal Error: '.$e->getMessage().'<div>');
        }
    }

    public static function step1() {
        if (!is_file(_INSTALL_PATH.'/template/step1.phtml')) {
            throw new Exception('Can\'t find this file ('._INSTALL_PATH.'/template/step1.phtml).');
        }
        $navigation = false;
        $error = false;
        if (Request::isPostRequest() && Request::getVar('submit', Request::M_POST)) {
            $path = trim(Request::getVar('path', Request::M_POST));
            $site = trim(Request::getVar('site', Request::M_POST), '/');
            if ($path !== '' && (!is_dir(realpath($path.'/application/')) || !is_dir(realpath($path.'/library/')))) {
                $error = true;
            } else {
                $entered = true;
                if ($path === '') {
                    if (is_dir(realpath('../').'/seotoaster_core/')) {
                        $path = realpath('../').'/seotoaster_core/';
                        $entered = false;
                    } else {
                        throw new Exception("Can't find folder 'seotoaster_core' (".realpath('../')."/seotoaster_core/)");
                    }
                }
                Session::set('pathToCore', realpath($path).'/');
                Session::set('siteName', $site);
                Session::set('pathToRoot', realpath('../').'/');
                if (!$entered) {
                    $path = '';
                }
                $navigation = true;
            }
        }
        include_once _INSTALL_PATH.'/template/step1.phtml';
    }

    public static function step2() {
        if (!is_file(_INSTALL_PATH.'/template/step2.phtml')) {
            throw new Exception('Can\'t find this file ('._INSTALL_PATH.'/template/step2.phtml).');
        }
        $error = false;
        
        $version = version_compare(PHP_VERSION, '5.0.0', '>') ? true : false;
        include_once _INSTALL_PATH.'/template/step2.phtml';
    }

    public static function step3() {
        if (!is_file(_INSTALL_PATH.'/template/step3.phtml')) {
            throw new Exception('Can\'t find this file ('._INSTALL_PATH.'/template/step3.phtml).');
        }
        $navigation = false;
        $error = false;
        $message = '';
        $siteName = trim(Session::get('siteName'));
        if ($siteName !== '') {
            $pathToConfig = Session::get('pathToCore').'application/configs/'.$siteName.'/';
            if (!is_dir($pathToConfig) && !@mkdir($pathToConfig)) {
                throw new Exception("Can't create folder '$siteName' ($pathToConfig)");
            } else {
                if (!copy(Session::get('pathToCore').'application/configs/application.ini', $pathToConfig.'application.ini')) {
                    throw new Exception('Failed to copy '.Session::get('pathToCore').'application/configs/application.ini');
                }
                if (!copy(Session::get('pathToCore').'application/configs/routesext.xml', $pathToConfig.'routesext.xml')) {
                    throw new Exception('Failed to copy '.Session::get('pathToCore').'application/configs/routesext.xml');
                }
            }
        }
        if (Request::isPostRequest() && Request::getVar('submit', Request::M_POST)) {
            require_once 'includes/mysql.php';
            $host = trim(Request::getVar('host', Request::M_POST));
            $db = trim(Request::getVar('db', Request::M_POST));
            $user = trim(Request::getVar('user', Request::M_POST));
            $password = trim(Request::getVar('password', Request::M_POST));
            try {
                $sqlFile = Helpers::getContent(_INSTALL_PATH.'/sql/seotoaster.sql');
                $arrayQueries = Helpers::splitSql($sqlFile);
                $mysql = new MySQL($host, $user, $password, $db);
                $mysql->connect();
                foreach ($arrayQueries as $query) {
                    $mysql->query($query);
                }
                $mysql->disconnect();
                Session::set('host', $host);
                Session::set('db', $db);
                Session::set('user', $user);
                Session::set('password', $password);
                $navigation = true;
            } catch (Exception $e) {
                $error = true;
                $message = $e->getMessage();
                $navigation = false;
            }
        }
        include_once _INSTALL_PATH.'/template/step3.phtml';
    }

    public static function step4() {
        if (!is_file(_INSTALL_PATH.'/template/step4.phtml')) {
            throw new Exception('Can\'t find this file ('._INSTALL_PATH.'/template/step4.phtml).');
        }
        $navigation = false;
        $error = false;
        $message = '';
        if (Request::isPostRequest() && Request::getVar('submit', Request::M_POST)) {
            require_once 'includes/mysql.php';
            $site_url = trim(Request::getVar('site_url', Request::M_POST));
            $email = trim(Request::getVar('email', Request::M_POST));
            $small = intval(Request::getVar('small', Request::M_POST));
            $medium = intval(Request::getVar('medium', Request::M_POST));
            $large = intval(Request::getVar('large', Request::M_POST));
            $smtp = trim(Request::getVar('smtp', Request::M_POST)) === 'on' ? true : false;
            $smtp_host = trim(Request::getVar('smtp_host', Request::M_POST));
            $smtp_login = trim(Request::getVar('smtp_login', Request::M_POST));
            $smtp_password = trim(Request::getVar('smtp_password', Request::M_POST));
            $login = trim(Request::getVar('login', Request::M_POST));
            $password = trim(Request::getVar('password', Request::M_POST));
            $siteName = Session::get('siteName');
     
            try {
                $mysql = new MySQL(Session::get('host'), Session::get('user'), Session::get('password'), Session::get('db'));
                $mysql->connect();
                $mysql->query("update config set value = '$email' where name = 'admin_email'");
                $mysql->query("update config set value = ".($small > 0 ? $small : 200)." where name = 'img_small'");
                $mysql->query("update config set value = ".($medium > 0 ? $medium : 300)." where name = 'img_medium'");
                $mysql->query("update config set value = ".($large > 0 ? $large : 400)." where name = 'img_large'");
                if ($smtp) {
                    $mysql->query("update config set value = 1 where name = 'use_smtp'");
                    $mysql->query("update config set value = '$smtp_host' where name = 'smtp_host'");
                    $mysql->query("update config set value = '$smtp_login' where name = 'smtp_login'");
                    $mysql->query("update config set value = '$smtp_password' where name = 'smtp_password'");
                }
                $mysql->query("insert into `user`(`role_id`,`id_user_seosamba`,`login`,`password`,`email`,`status`,`nickname`,`last_login`,`ipaddress`,`reg_date`) 
                        values (3, 0, '$login', md5('$password'), '$email', 'active', 'admin', NULL, NULL, NOW())");
                if ($siteName !== '') {
                    $mysql->query("update config set value = '$siteName' where name = 'site_name' limit 1");
                }
                $mysql->disconnect();
                $site_url = $site_url.($site_url[strlen($site_url)-1] != '/' ? '/' : '');
                self::saveApplication($site_url);
                //self::saveRoutes($site_url);
                Session::set('siteURL', $site_url);
                $navigation = true;
            } catch (Exception $e) {
                $error = true;
                $message = $e->getMessage();
                $navigation = false;
            }
        }
        include_once _INSTALL_PATH.'/template/step4.phtml';
    }

    public static function step5() {
        if (!is_file(_INSTALL_PATH.'/template/step5.phtml')) {
            throw new Exception('Can\'t find this file ('._INSTALL_PATH.'/template/step5.phtml).');
        }
        include_once _INSTALL_PATH.'/template/step5.phtml';
    }

    public static function step6() {
        if (!is_file(_INSTALL_PATH.'/template/step6.phtml')) {
            throw new Exception('Can\'t find this file ('._INSTALL_PATH.'/template/step6.phtml).');
        }
        self::saveHtaccessFile();
        self::saveSiteName();
        $siteURL = Session::get('siteURL');
        include_once _INSTALL_PATH.'/template/step6.phtml';
    }

    public static function getStep() {
        $step = intval(Request::getVar('step', Request::M_POST));
        if ($step >= 1 && $step <= 6) {
            return 'step'.$step;
        } else {
            return 'step1';
        }
    }

    public static function saveApplication($siteURL) {
        $config = Helpers::getContent(_INSTALL_PATH.'/template/config.tpl');
        $config = str_replace('{host}', Session::get('host'), $config);
        $config = str_replace('{user}', Session::get('user'), $config);
        $config = str_replace('{password}', Session::get('password'), $config);
        $config = str_replace('{db}', Session::get('db'), $config);
        $config = str_replace('{site_url}', $siteURL, $config);
        $config = str_replace('{path}', Session::get('pathToRoot'), $config);
        $siteName = trim(Session::get('siteName'));

        if ($siteName !== '') {
            $pathToConfig = Session::get('pathToCore').'application/configs/'.$siteName.'/';
            if (is_dir($pathToConfig)) {
                if (false === @file_put_contents($pathToConfig.'application.ini', $config)) {
                    throw new Exception("Can't save file 'application.ini' ($pathToConfig application.ini)");
                }
            } else {
                throw new Exception("Can't find folder '$siteName' ($pathToConfig)");
            }
        } else {
            if (false === @file_put_contents(Session::get('pathToCore').'application/configs/application.ini', $config)) {
                throw new Exception("Can't save file 'application.ini' (".Session::get('pathToCore')."application/configs/application.ini)");
            }
        }
    }

    /*public static function saveRoutes($siteURL) {
		if (is_file(realpath('../').'/system/misc/routest.tpl.phtml')) {
            $content = Helpers::getContent(realpath('../').'/system/misc/routest.tpl.phtml');
			$url = '';
			$parseURL = parse_url($siteURL);            
			if (isset($parseURL['path'])) {
				$tmpUrl = trim($parseURL['path'], '/');
				if ($tmpUrl != '') {
					$url = $tmpUrl;
				}
			}
			$content = str_replace('%sitedir%', $url, $content);
            $siteName = trim(Session::get('siteName'));
            
            if ($siteName !== '') {
                $pathToConfig = Session::get('pathToCore').'application/configs/'.$siteName.'/';
                if (is_dir($pathToConfig)) {
                    if (false === @file_put_contents($pathToConfig.'routesext.xml', $content)) {
                        throw new Exception("Can't save file (".$pathToConfig."routesext.xml).");
                    }
                } else {
                    throw new Exception("Can't find folder '$siteName' ($pathToConfig)");
                }
            } else {
                if(false === @file_put_contents(Session::get('pathToCore').'application/configs/routesext.xml', $content)) {
                    throw new Exception("Can't save file (".Session::get('pathToCore')."application/configs/routesext.xml).");
                }
            }
		} else {
			throw new Exception("Can't find file (".realpath('../')."/system/misc/routest.tpl.phtml) or this file doesn't exist.");
		}
	}*/

    public static function saveHtaccessFile() {
        $siteURL = Session::get('siteURL');
        $parsedUrl = parse_url($siteURL);
		$siteDir = $parsedUrl['path'];
		$siteDir = ($siteDir == '/') ? '' : ltrim($siteDir, '/');
		if (is_file(_INSTALL_PATH.'/template/htaccess.tpl')) {
            $content = Helpers::getContent(_INSTALL_PATH.'/template/htaccess.tpl');
			$content = str_replace('{site_url}', $siteURL, $content);
            $content = str_replace('{site_host}', $parsedUrl['host'], $content);
            $content = str_replace('{site_dir}', $siteDir, $content);
			if (false === @file_put_contents(Session::get('pathToRoot').'.htaccess', $content)) {
				throw new Exception("Can't save file (".Session::get('pathToRoot').".htaccess).");
			}
		} else {
			throw new Exception("Can't find file ("._INSTALL_PATH."/template/htaccess.tpl) or this file doesn't exist.");
		}
    }

    public static function saveSiteName() {
        $siteName = trim(Session::get('siteName'));
        $pathToCore = trim(Session::get('pathToCore'));
        $pathToRoot = trim(Session::get('pathToRoot'));
        
        //if ($siteName !== '' || ($pathToCore !== $pathToRoot.'seotoaster_core/')) {
            $content = "<?php \n";
            $content .= "define ('APPLICATION_PATH', '".$pathToCore."application'); \n";
            $content .= "define ('SITE_NAME', '".($siteName !== '' ? $siteName.'/' : '')."'); \n";
            if (false === @file_put_contents($pathToRoot.'config.php', $content)) {
                throw new Exception('Can\'t save file ('.$pathToRoot.'config.php).');
            }
        //}
    }
}